package com.platform.api;

import com.platform.annotation.LoginUser;
import com.platform.entity.CollectVo;
import com.platform.entity.LikeRecordVo;
import com.platform.entity.UserVo;
import com.platform.service.ApiLikeRecordService;
import com.platform.service.ApiPostsService;
import com.platform.util.ApiBaseAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/like")
public class ApiLikeController extends ApiBaseAction {

    @Autowired
    private ApiLikeRecordService likeRecordService;
    @Autowired
    private ApiPostsService postsService;

    /**
     * 获取用户收藏
     */
    @Transactional
    @RequestMapping("addordelete")
    public Object addordelete(@LoginUser UserVo loginUser,
                              @RequestParam Integer typeId,//类型：0-故事社区
                              @RequestParam Integer valueId) {

        Map<String, Object> param = new HashMap<>();
        param.put("userId", loginUser.getUserId());
        param.put("typeId", typeId);
        param.put("valueId", valueId);

        List<LikeRecordVo> likeRecordVos = likeRecordService.queryList(param);

        //collectResult 收藏结果
        Integer likeRes;
        String handleType = "add";
        if (null == likeRecordVos || likeRecordVos.size() < 1) {
            LikeRecordVo likeRecordVo = new LikeRecordVo();
            likeRecordVo.setAddTime(new Date());
            likeRecordVo.setTypeId(typeId);
            likeRecordVo.setValueId(valueId);
            likeRecordVo.setUserId(loginUser.getUserId().intValue());
            //添加点赞记录
            likeRes = likeRecordService.save(likeRecordVo);
        } else {
            //取消点赞记录
            likeRes = likeRecordService.delete(likeRecordVos.get(0).getId());
            handleType = "delete";
        }

        if (likeRes > 0) {
            Map<String, Object> data = new HashMap<>();
            data.put("type", handleType);

            //todo 业务处理
            if (typeId == 0) {//社区故事
                if (handleType.equals("add")) {
                    postsService.updateLikeCount(valueId, 1);
                } else {
                    postsService.updateLikeCount(valueId, 0);
                }
            }

            return toResponsSuccess(data);
        }

        return toResponsFail("操作失败");
    }


}
